Vector Basics

Vectors are one of the key data structures in R which we wil be using. A vector is a 1 dimensional array that can hold character, numeric, or logical data elements.

We can create a vector by using the combine function c(). To use the function, we pass in the elements we want in the array, with each individual element separated by a comma.

Let's see some examples:

In [14]:
# Using c() to create a vector of numeric elements
nvec <- c(1,2,3,4,5)
In [15]:
class(nvec)
Out[15]:
'numeric'
In [16]:
# Vector of characters
cvec <- c('U','S','A')
In [17]:
class(cvec)
Out[17]:
'character'
In [18]:
lvec <- c(TRUE,FALSE)
In [19]:
lvec
Out[19]:
  1. TRUE
  2. FALSE
In [20]:
class(lvec)
Out[20]:
'logical'

Note that we can't mix data types of the elements in an array, R will convert the other elements in the array to force everything to be of the same data type. Later on we will learn about the list data structure that can take on multiple data types!

Here's a quick example of what happens with arrays given different data types:

In [31]:
v <- c(FALSE,2)
In [32]:
v
Out[32]:
  1. 0
  2. 2
In [26]:
class(v)
Out[26]:
'numeric'
In [28]:
v <- c('A',1)
In [29]:
v
Out[29]:
  1. 'A'
  2. '1'
In [30]:
class(v)
Out[30]:
'character'

Vector Names

We can use the names() function to assign names to each element in our vector. For example, imagine the folowing vector of a week of temperatures:

In [38]:
temps <- c(72,71,68,73,69,75,71)
In [39]:
temps
Out[39]:
  1. 72
  2. 71
  3. 68
  4. 73
  5. 69
  6. 75
  7. 71

We know we have 7 temperatures for 7 weekdays, but which temperature corresponds to which weekday? Does it start on Monday, Sunday, or another day of the week? This is where names() can be assigned in the following manner:

In [40]:
names(temps) <- c('Mon','Tue','Wed','Thu','Fri','Sat','Sun')

Now note what happens when we display the named vector:

In [41]:
temps
Out[41]:
Mon
72
Tue
71
Wed
68
Thu
73
Fri
69
Sat
75
Sun
71

We can now begin to see how the elements were assigned names! Depending on what IDE you are using, you may see the above displayed horizontally instead of vertically, that's totally fine!

We also don't have to rewrite the names vector over and over again, we can use simple use a variable name as a names() assignment, for example:

In [42]:
days <- c('Mon','Tue','Wed','Thu','Fri','Sat','Sun')
temps2 <- c(1,2,3,4,5,6,7)
names(temps2) <- days
In [43]:
temps2
Out[43]:
Mon
1
Tue
2
Wed
3
Thu
4
Fri
5
Sat
6
Sun
7

That's is for vector basics! Up next we will go over working with vectors.